package com.kcs.fxmargin.action;

import java.math.BigDecimal;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.kcs.common.utils.Constant;
import com.kcs.common.utils.commonUtils;
import com.kcs.fxmargin.action.form.CheckLimitOrderActionForm;
import com.kcs.fxmargin.action.form.LoginActionForm;
import com.kcs.fxmargin.bo.CheckLimitOrderBO;
import com.kcs.fxmargin.service.CheckLimitOrderService;

public class CheckLimitOrderAction extends FXAction {
	
	private Logger log = Logger.getLogger(Constant.LOG_FX);

	@Override
	public ActionForward process(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {

		CheckLimitOrderActionForm bean = null;
		CheckLimitOrderBO bo = null;
		CheckLimitOrderService svc = null;
		LoginActionForm userInfo = null;
		
		log.info("Begin : CheckLimitOrderAction : process");
		
		try{
			
			bean = (CheckLimitOrderActionForm)form;
			
			if(userInfo == null){
				userInfo = (LoginActionForm) request.getSession().getAttribute(Constant.LOGIN_DATA_SESSION);
				if(userInfo != null){
					bean.setUserLoginId(userInfo.getUserId());
					bean.setUserLoginName(userInfo.getUserName());
					bean.setUserLoginRoleId(userInfo.getRoleId());
				}
			}
			
			if(bean.getTranCode().equals("")){
				bean.resetForm();
			
			}else if(bean.getTranCode().equals("resetResult")){
				//bean.setInAmountFwCt("");
				bean.setPreOrderAmount("");
				bean.setCustLimitAvailable("");
				bean.setCustOverLimit("");
				bean.setFxLimitAvailable("");
				bean.setFxOverLimit("");
			
			}else if(bean.getTranCode().equals("checkLimit")){
				
				if(validateCheckLimit(bean,request)){
					svc = new CheckLimitOrderService();
					bo = new CheckLimitOrderBO();
					bo.setInCifNo(bean.getInCifNo());
					bo.setInCustomerName(bean.getInCustomerName());
					bo.setInAmountFwCt(bean.getInAmountFwCt());
					bo.setCreateUser(bean.getUserLoginId());
					bo.setCustInfoId(bean.getCustInfoId());
					
					bo = svc.checkLimit(bo);
					
					bean.setPreOrderAmount(bo.getPreOrderAmount());
					bean.setCustLimitAvailable(bo.getCustLimitAvailable());
					bean.setCustOverLimit(bo.getCustOverLimit());
					bean.setFxLimitAvailable(bo.getFxLimitAvailable());
					bean.setFxOverLimit(bo.getFxOverLimit());
					bean.setMarginLimit(bo.getMarginLimit());
					
					if(bo.isProcessSuccess()){
						bean.setCustOverLimit(getOverLimit(bean.getInAmountFwCt(),bean.getCustLimitAvailable()));
						bean.setFxOverLimit(getOverLimit(bean.getInAmountFwCt(),bean.getFxLimitAvailable()));
						
						if(isOverLimit(bean.getCustOverLimit()) && isOverLimit(bean.getFxOverLimit())){
							request.setAttribute(Constant.ERR_ATTR,Constant.ERR_OVER_LIMIT_CUSTOMER_AND_FX);
							request.setAttribute(Constant.OVER_LIMIT_CUST_ATTR,Constant.ERR_OVER_LIMIT_CUSTOMER);
							request.setAttribute(Constant.OVER_LIMIT_FX_ATTR,Constant.ERR_OVER_LIMIT_FX.replace("#,###.00", commonUtils.decimalFormat(getMarginLimitError(bean.getFxOverLimit(),bo.getInitialMargin()))));
						}else if(isOverLimit(bean.getCustOverLimit())){
							request.setAttribute(Constant.OVER_LIMIT_CUST_ATTR,Constant.ERR_OVER_LIMIT_CUSTOMER);
							request.setAttribute(Constant.ERR_ATTR,Constant.ERR_OVER_LIMIT_CUSTOMER);
						}else if(isOverLimit(bean.getFxOverLimit())){
							request.setAttribute(Constant.OVER_LIMIT_FX_ATTR,Constant.ERR_OVER_LIMIT_FX.replace("#,###.00", commonUtils.decimalFormat(getMarginLimitError(bean.getFxOverLimit(),bo.getInitialMargin()))));
							request.setAttribute(Constant.ERR_ATTR,Constant.ERR_OVER_LIMIT_FX.replace("#,###.00", commonUtils.decimalFormat(getMarginLimitError(bean.getFxOverLimit(),bo.getInitialMargin()))));
						}else{
							request.setAttribute(Constant.COMPLETE_ATTR, "Check Limit Complete");
						}

						System.out.println(">> Before >>  pre-order : "+bean.getPreOrderAmount());
						
						//Decimal Format
						bean.setPreOrderAmount(commonUtils.decimalFormat(bean.getPreOrderAmount()));
						bean.setCustLimitAvailable(commonUtils.decimalFormat(bean.getCustLimitAvailable()));
						bean.setCustOverLimit(commonUtils.decimalFormat(bean.getCustOverLimit()));
						bean.setFxLimitAvailable(commonUtils.decimalFormat(bean.getFxLimitAvailable()));
						bean.setFxOverLimit(commonUtils.decimalFormat(bean.getFxOverLimit()));
						bean.setMarginLimit(commonUtils.decimalFormat(bean.getMarginLimit()));
						
						System.out.println(">> After >>  pre-order : "+bean.getPreOrderAmount());
						
						
					}else{
						request.setAttribute(Constant.ERR_ATTR,"Check Limit Fail: Please examine system data or try again.");
					}	
				
				}
			}
			
			
		}catch(Exception e){
			e.printStackTrace();
			request.setAttribute(Constant.ERR_ATTR, e+"");
			
		}finally{
			if(bean != null){
				bean.setTranCode("");
			}
		}

		log.info("End : CheckLimitOrderAction : process");
		return mapping.findForward("checkLimitOrder");

	}
	
	private String getOverLimit(String amount, String limit)throws Exception{
		BigDecimal bAmount = new BigDecimal(amount);
		BigDecimal bLimit = new BigDecimal(limit);
		bLimit = bLimit.subtract(bAmount);
		return (bLimit.signum()<0)?bLimit.toString():"0";
	}
	
	private boolean isOverLimit(String overLimit)throws Exception{
		return Double.parseDouble(overLimit) < 0;
	}
	
	private boolean validateCheckLimit(CheckLimitOrderActionForm bean, HttpServletRequest request){
		boolean result = true;
		log.info("Begin : CheckLimitOrderAction : validateCheckLimit");
		if (bean.getInCifNo().equals("") || bean.getInAmountFwCt().equals("") || bean.getCustInfoId().equals("")) {
			request.setAttribute(Constant.ERR_ATTR, Constant.ERR_REQUIRED_COMPLETE);
			result = false;
		}
		log.info("End : CheckLimitOrderAction : validateCheckLimit");
		return result;
	}
	
	private String getMarginLimitError(String fxMarginOverlimit, String initialMargin)throws Exception{
		BigDecimal b1 = new BigDecimal(fxMarginOverlimit);
		BigDecimal b2 = new BigDecimal(initialMargin);
		
		b1 = b1.multiply(b2);
		b1 = b1.abs();
		return b1.toString();
	}

}
